<template>
  <div class="app-container">
    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="结算单列表" name="settlement"></el-tab-pane>
      <el-tab-pane label="未结算采购单列表" name="unsettledOrder"></el-tab-pane>
    </el-tabs>

    <!-- 结算单列表 -->
    <div v-if="activeTab === 'settlement'">
      <el-form :model="queryParams1" ref="queryForm1" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="结算单编号" prop="sn">
          <el-input
            v-model="queryParams1.sn"
            placeholder="请输入结算单编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input
            v-model="queryParams1.supplierName"
            placeholder="请输入供应商名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>



      <el-table v-loading="loading" :data="settlementList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="结算单编号" align="center" prop="sn" />
        <el-table-column label="结算时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="制作日期" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="制作人" align="center" prop="creator" />
        <el-table-column label="结算金额" align="center" prop="totalPrice">
          <template slot-scope="scope">
            <span>¥{{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="handleCancel(scope.row)"
            >取消</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-printer"
              @click="handlePrint(scope.row)"
            >打印</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total1>0"
        :total="total1"
        :page.sync="queryParams1.pageNum"
        :limit.sync="queryParams1.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 未结算采购单列表 -->
    <div v-if="activeTab === 'unsettledOrder'">
      <el-form :model="queryParams2" ref="queryForm2" size="small" :inline="true" v-show="showSearch" label-width="150px">
        <el-form-item label="入库单编号" prop="sn">
          <el-input
            v-model="queryParams2.sn"
            placeholder="请输入入库单编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input
            v-model="queryParams2.supplierName"
            placeholder="请输入供应商名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 修改后的未结算采购单列表表格部分 -->
      <el-table v-loading="loading" :data="entryList" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="入库单编号"
          align="center"
          prop="sn"
          :min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="入库日期"
          align="center"
          prop="entryTime"
          :min-width="120"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.entryTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="所属部门"
          align="center"
          prop="deptName"
          :min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="仓库"
          align="center"
          :min-width="120"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.warehouseName }}
          </template>
        </el-table-column>
        <el-table-column
          label="经手人"
          align="center"
          prop="handledByName"
          :min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          :min-width="120"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status !== '已结算'"
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAddToSettlement(scope.row)"
            >加入结算单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total2>0"
        :total="total2"
        :page.sync="queryParams2.pageNum"
        :limit.sync="queryParams2.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改供应商结算单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="结算单编号" prop="sn">
              <el-input v-model="form.sn" placeholder="请输入结算单编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-select
                v-model="form.supplierId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入供应商名称"
                :remote-method="remoteSearchSupplier"
                :loading="supplierLoading"
                @change="handleSupplierChange"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.contact }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="结算开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结算开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结算结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">结算明细</el-divider>

        <el-table :data="form.details" border>
          <el-table-column label="入库单号" prop="entrySn" width="150" />
          <el-table-column label="入库日期" prop="entryTime" width="120">
            <template slot-scope="scope">
              {{ parseTime(scope.row.entryTime, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.amount }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleRemoveDetail(scope.$index)"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row style="margin-top: 20px">
          <el-col :span="24" style="text-align: right">
            <span style="font-size: 16px; margin-right: 20px">合计金额: ¥{{ form.totalPrice || 0 }}</span>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSettlement, getSettlement, delSettlement, addSettlement, updateSettlement, cancelSettlement, printSettlement } from "@/api/procurementmanagement/settlement";
import { listEntry, getEntry, updateEntry } from "@/api/procurementmanagement/entry";
import { listSupplier } from "@/api/procurementmanagement/plan";
import { addExpenses, deleteExpensesBySourceSn } from "@/api/finance/expenses";


export default {
  name: "Settlement",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total1: 0,
      total2: 0,
      // 当前选中的标签
      activeTab: "settlement",
      // 供应商结算单表格数据
      settlementList: [],
      // 未结算入库单数据
      entryList: [],
      // 供应商选项
      supplierOptions: [],
      supplierLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        supplierName: null
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        supplierName: null,
        status: '审核通过',
        settlementStatus: '未结算',
        warehouseName:null
      },
      // 表单参数
      form: {
        details: []
      },
      // 表单校验
      rules: {
        supplierId: [{ required: true, message: "请选择供应商", trigger: "change" }],
        startTime: [{ required: true, message: "请选择结算开始时间", trigger: "change" }],
        endTime: [{ required: true, message: "请选择结算结束时间", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      if (this.activeTab === "settlement") {
        listSettlement(this.queryParams1).then(response => {
          this.settlementList = response.rows;
          this.total1 = response.total;
          this.loading = false;
        });
      } else {
        listEntry({
          pageNum: 1,
          pageSize: 10,
          sn: null,
          supplierName: null,
          status: '审核通过',
          supplierSettlementFlag: 0, // 使用supplierSettlementFlag代替settlementStatus
          warehouseName: null
        }).then(response => {
          this.entryList = response.rows;
          this.total2 = response.total;
          this.loading = false;
        });
      }
    },

    /** 切换标签 */
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.resetQuery();
      this.getList();
    },

    // 取消操作
    async handleCancel(row) {
      try {
        this.$modal.confirm('是否确认取消结算单编号为"' + row.sn + '"的结算单？').then(async () => {
          this.loading = true;
          const response = await cancelSettlement(row.id);

          if (response.code === 200) {
            this.$modal.msgSuccess("取消成功");

            // 强制刷新当前标签页数据
            if (this.activeTab === 'settlement') {
              await this.getList(); // 重新加载结算单列表
            }

            // 刷新未结算列表
            await this.getUnsettledList();

            // 清除可能的缓存
            this.$forceUpdate();
          } else {
            this.$message.error(response.msg || "取消失败");
          }
        }).catch(() => {
          this.$message.info("已取消操作");
        });
      } catch (error) {
        console.error("取消操作失败:", error);
        this.$message.error("操作失败: " + (error.message || error));
      } finally {
        this.loading = false;
      }
    },

    // 新增方法：获取未结算列表
    async getUnsettledList() {
      if (this.activeTab === 'unsettledOrder') {
        this.loading = true;
        try {
          const response = await listEntry({
            status: '审核通过',
            supplierSettlementFlag: 0
          });
          this.entryList = response.rows;
          this.total2 = response.total;
        } catch (error) {
          console.error("获取未结算列表失败:", error);
        } finally {
          this.loading = false;
        }
      }
    },

    // 打印操作
    handlePrint(row) {
      printSettlement(row.id).then(response => {
        this.$modal.msgSuccess("打印成功");
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      if (this.activeTab === "settlement") {
        this.queryParams1.pageNum = 1;
      } else {
        this.queryParams2.pageNum = 1;
      }
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      if (this.activeTab === "settlement") {
        this.resetForm("queryForm1");
      } else {
        this.resetForm("queryForm2");
      }
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 生成结算单编号 SS + 年月日 + 4位序列号 (如 SS202503140016)
    generateSettlementSn() {
      const now = new Date();
      const datePart = now.toISOString().slice(0, 10).replace(/-/g, ''); // 格式: YYYYMMDD
      const randomPart = Math.floor(1000 + Math.random() * 9000); // 4位随机数
      return `SS${datePart}${randomPart}`;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增结算单";
      // 生成结算单编号
      this.form.sn = this.generateSettlementSn();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids[0];
      getSettlement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改结算单";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的结算单？').then(() => {
        return delSettlement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 远程搜索供应商
    remoteSearchSupplier(query) {
      if (query) {
        this.supplierLoading = true;
        listSupplier({ name: query }).then(response => {
          this.supplierOptions = response.rows;
          this.supplierLoading = false;
        });
      }
    },

    // 供应商选择变化
    handleSupplierChange(val) {
      const supplier = this.supplierOptions.find(item => item.id === val);
      if (supplier) {
        this.form.supplierName = supplier.name;
      }
    },

    // 添加入库单到结算单
    async handleAddToSettlement(row) {
      try {
        // 1. 获取入库单商品明细并计算总价
        const entryDetailResponse = await getEntry(row.id);
        const entryDetail = entryDetailResponse.data;

        // 调试日志 - 检查返回的数据结构
        console.log('入库单详情:', entryDetail);

        // 计算入库单中所有商品的总价
        let totalPrice = 0;

        // 检查是否有商品明细数据
        if (entryDetail.entryProducts && entryDetail.entryProducts.length > 0) {
          totalPrice = entryDetail.entryProducts.reduce((sum, product) => {
            const price = product.totalPrice || 0;
            console.log(`商品 ${product.name} 金额: ${price}`);
            return sum + price;
          }, 0);
        } else {
          // 如果没有商品明细，尝试使用入库单的总价
          console.warn('没有找到商品明细，使用入库单总价作为回退');
          totalPrice = row.totalPrice || 0;
        }

        console.log('计算出的总价:', totalPrice);

        // 2. 创建结算单数据
        const settlementData = {
          sn: this.generateSettlementSn(),
          supplierId: row.supplierId,
          supplierName: row.supplierName,
          startTime: new Date().toISOString(),
          endTime: new Date().toISOString(),
          totalPrice: totalPrice,
          creator: this.$store.state.user.name,
          entryIds: [row.id] // 传入关联的入库单ID
        };

        // 3. 提交结算单
        const settlementResponse = await addSettlement(settlementData);
        console.log('结算单响应:', settlementResponse);

        if (settlementResponse.code === 200) {
          // 4. 更新入库单状态
          const settlementId = settlementResponse.data?.id || settlementResponse.id;
          const updateResponse = await updateEntry({
            id: row.id,
            status: '已结算',
            supplierSettlementFlag: 1,
            supplierSettlementId: settlementId
          });

          if (updateResponse.code === 200) {
            // 5. 创建财务记录
            const financeData = {
              sourceType: "采购",
              sourceSn: settlementData.sn,
              amount: totalPrice,
              amountType: "2",
              creator: this.$store.state.user.name
            };
            await addExpenses(financeData);

            // 6. 刷新列表
            this.$message.success("添加结算单成功");
            this.getList();
          } else {
            this.$message.error("更新入库单状态失败");
            // 如果更新入库单状态失败，可能需要回滚结算单创建
            await delSettlement(settlementId);
          }
        } else {
          this.$message.error("添加结算单失败");
        }
      } catch (error) {
        console.error('添加结算单出错:', error);
        this.$message.error("操作失败: " + (error.message || error));
      }
    },

    // 移除结算明细
    handleRemoveDetail(index) {
      this.form.details.splice(index, 1);
      this.calculateTotal();
    },

    // 计算总金额
    calculateTotal() {
      this.form.totalPrice = this.form.details.reduce((sum, item) => sum + (item.amount || 0), 0);
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        supplierId: null,
        supplierName: null,
        startTime: null,
        endTime: null,
        totalPrice: 0,
        details: []
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSettlement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSettlement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    }
  }
};
</script>

<style scoped>
.el-divider {
  margin: 15px 0;
}
</style>
